function [r, pos] = extractOverlayBlock( img, B, varargin)
if nargin < 2
    B = 64;
end
B2 = floor(B / 2);
nargv = length(varargin);
if nargv == 0
    %varargin{1} = @DefaultFeatureBlock;
    varargin{1} = @AverageBlock;
    nargv = 1;
else
    for i = 1:nargv
        func = varargin{i};
        if ~isa(func, 'function_handle')
            error('All inputs in varargin must be handler functions.');
        end
    end
end

clear r  pos;
[M, N, S] = size(img);
count = 0;
L = 0;
for i = 1:B2:M-B+1
    for j = 1:B2:N-B+1
        block = img(i:i+B-1,j:j+B-1,:);
        count = count + 1;
        for k = 1:nargv
            f = 0;
            r{count} = zeros(1, L);
            if (count == 1) % first run
                q = varargin{k}(block);
                L = L + length(q);
                r{count} = [r{count} q];
            else
                q = varargin{k}(block);
                r{count}(f+1:f+length(q)) = q;
            end
        end
        pos{count} = [i i+B-1 j j+B-1];
    end
end
end

function f = DefaultFeatureBlock(block)
    f = block(:);
end

function f = AverageBlock(block)
    S = size(block,3);
    f = zeros(1, S);
    for i = 1:S
        f(i) = sum(sum(block(:, :, i))) / size(block, 1) / size(block, 2);
    end
end
